<?php
function getTranslationItems($catID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_sysTranslatedSiteText WHERE SiteArea = '$catID' ORDER BY TransLabel";
	$result = mysql_db_query($dbname,$sql);
	
	$stringJSON   = '({"TranslationItems":[';
	while ($value = mysql_fetch_assoc($result)) {
		$stringJSON .= Zend_Json::encode($value).',';		
	}	
	$stringJSON = substr($stringJSON,0,-1);
	$stringJSON .= ']})';
	
	return $stringJSON;
}

function saveTranslationItem($phpJSON) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON  = stripslashes($phpJSON);
	$phpArray = Zend_Json::decode($phpJSON);
		
	$catID   = $phpArray['catID'];
	$itemID  = $phpArray['itemID'];
	$label   = $phpArray['label'];
	$english = $phpArray['english'];
	$spanish = $phpArray['spanish'];
	$russian = $phpArray['russian'];
	
	if (empty($itemID)) {
		/*
		 * We're adding a new translation entry
		 */
		$sql = "INSERT into cdc_sysTranslatedSiteText (
				SiteArea,
				TransLabel,
				TransEnglish,
				TransSpanish,
				TransRussian,
				TimestampUpdate,
				UseridEntry
				) values (
				'$catID',
				'$label',
				'$english',
				'$spanish',
				'$russian',
				'".time()."',
				'".$_SESSION['userid']."'
				)";
	} else {
		$sql = "UPDATE cdc_sysTranslatedSiteText SET
				TransEnglish    = '$english',
				TransSpanish    = '$spanish',
				TransRussian    = '$russian',
				TimestampUpdate = '".time()."',
				UseridUpdate    = '".$_SESSION['userid']."'
				WHERE
				TID = '$itemID'";
	}
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Update translations.tmx
	 */
	updateTranslationXML();
}

function updateTranslationXML() {
	global $dbname, $db, $db_selected;
	$tmxFile = ROOT_DIR.'languages/translations.tmx';
	$tmxFileHandle = fopen($tmxFile, "w");
	$tmxFileContent = '<?xml version="1.0" encoding="UTF-8"?>
			<!DOCTYPE tmx SYSTEM "tmx14.dtd">
			<tmx version="1.4">
				<header adminlang="en-us"></header>
				<body>';
	
	/*
	 * Pull all translation items and dump into XML file
	 */

	$sql = "SELECT * from cdc_sysTranslatedSiteText";
	$result = mysql_db_query($dbname,$sql);
	
	while ($value = mysql_fetch_assoc($result)) {
		$transLabel   = $value['TransLabel'];
		$transEnglish = $value['TransEnglish'];
		$transSpanish = $value['TransSpanish'];
		$transRussian = $value['TransRussian'];
		
		$tmxFileContent .= '<tu tuid="'.$transLabel.'">'."\n";
		$tmxFileContent .= '<tuv xml:lang="en"><seg>'.$transEnglish.'</seg></tuv>'."\n";
		$tmxFileContent .= '<tuv xml:lang="es"><seg>'.$transSpanish.'</seg></tuv>'."\n";
		$tmxFileContent .= '<tuv xml:lang="ru"><seg>'.$transRussian.'</seg></tuv>'."\n";
		$tmxFileContent .= '</tu>'."\n";
	}
	
	$tmxFileContent .= '</body></tmx>';
	echo $tmxFileContent;
	fwrite($tmxFileHandle, $tmxFileContent);
	fclose($tmxFileHandle);
}

?>